<template>
  <view class="warehouse-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <text class="page-title">质检记录查询</text>
    </view>

    <!-- 查询条件区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">查询条件</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view class="form-group">
            <text class="form-label">取样编号</text>
            <input
              class="form-input"
              v-model.trim="searchForm.sampleCode"
              placeholder="请输入取样编号"
            />
            </view>
          <view class="form-group">
            <text class="form-label">炉次号</text>
          <input
            class="form-input"
              v-model.trim="searchForm.furnaceNo"
              placeholder="请输入炉次号"
          />
      </view>
    </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">批次号</text>
            <input
              class="form-input"
              v-model.trim="searchForm.batchNo"
              placeholder="请输入批次号"
            />
          </view>
          <view class="form-group">
            <text class="form-label">钢种名称</text>
            <input
              class="form-input"
              v-model.trim="searchForm.steelGradeName"
              placeholder="请输入钢种名称"
            />
          </view>
          </view>

              <view class="form-row">
                <view class="form-group">
            <text class="form-label">标准名称</text>
            <input
              class="form-input"
              v-model.trim="searchForm.standName"
              placeholder="请输入标准名称"
            />
          </view>
          <view class="form-group">
            <text class="form-label">创建时间（开始）</text>
                  <picker
                    class="form-picker"
                    mode="date"
              :value="searchForm.createTimeStart"
              @change="(e) => (searchForm.createTimeStart = e.detail.value)"
                  >
                    <view class="picker-content">
                <text>{{ searchForm.createTimeStart || "请选择开始日期" }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>
        </view>

        <view class="form-row">
                <view class="form-group">
            <text class="form-label">创建时间（结束）</text>
                  <picker
                    class="form-picker"
                    mode="date"
              :value="searchForm.createTimeEnd"
              @change="(e) => (searchForm.createTimeEnd = e.detail.value)"
                  >
                    <view class="picker-content">
                <text>{{ searchForm.createTimeEnd || "请选择结束日期" }}</text>
                      <text class="picker-arrow">></text>
                    </view>
                  </picker>
                </view>
          <view class="form-group"></view>
              </view>

        <!-- 查询按钮 -->
        <view class="form-row button-row">
          <button class="btn-reset" @click="handleReset">重置</button>
          <button class="btn-submit" @click="handleSearch">查询</button>
                </view>
                </view>
              </view>

    <!-- 主表列表区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">质检记录列表</text>
        <text class="section-count" v-if="pagination.total > 0">
          共 {{ pagination.total }} 条
        </text>
                </view>

      <view class="table-container">
        <view class="table-header">
          <view class="header-cell" style="flex: 0.5">序号</view>
          <view class="header-cell" style="flex: 1.2">取样编号</view>
          <view class="header-cell" style="flex: 1">炉次号</view>
          <view class="header-cell" style="flex: 1">批次号</view>
          <view class="header-cell" style="flex: 1.2">钢种名称</view>
          <view class="header-cell" style="flex: 1.2">标准名称</view>
          <view class="header-cell" style="flex: 1">创建时间</view>
          <view class="header-cell" style="flex: 0.8">业务状态</view>
              </view>

        <view class="table-body">
          <view
            v-for="(item, index) in masterTableList"
            :key="item.id || index"
            class="table-row"
            :class="{ expanded: expandedRows.includes(item.id) }"
            @tap="toggleRowExpand(item.id)"
          >
            <view class="table-cell" style="flex: 0.5">
              {{ (pagination.pageNo - 1) * pagination.pageSize + index + 1 }}
                </view>
            <view class="table-cell" style="flex: 1.2">{{ item.sampleCode || "-" }}</view>
            <view class="table-cell" style="flex: 1">{{ item.furnaceNo || "-" }}</view>
            <view class="table-cell" style="flex: 1">{{ item.batchNo || "-" }}</view>
            <view class="table-cell" style="flex: 1.2">{{ item.steelGradeName || "-" }}</view>
            <view class="table-cell" style="flex: 1.2">{{ item.standName || "-" }}</view>
            <view class="table-cell" style="flex: 1">
              {{ formatDateTime(item.createTime) || "-" }}
                </view>
            <view class="table-cell" style="flex: 0.8">{{ item.busStatus || "-" }}</view>
              </view>

          <!-- 空数据提示 -->
          <view v-if="masterTableList.length === 0 && !loading" class="empty-tip">
            <text>暂无数据</text>
                </view>
                </view>
              </view>

      <!-- 分页控件 -->
      <view class="pagination-container" v-if="pagination.total > 0">
        <view class="pagination-info">
          <text>第 {{ pagination.pageNo }} / {{ totalPages }} 页</text>
                </view>
        <view class="pagination-buttons">
          <button
            class="pagination-btn"
            :disabled="pagination.pageNo <= 1"
            @click="handlePrevPage"
          >
            上一页
                </button>
                <button
            class="pagination-btn"
            :disabled="pagination.pageNo >= totalPages"
            @click="handleNextPage"
          >
            下一页
                </button>
              </view>
            </view>
          </view>

    <!-- 子表列表区域（展开时显示） -->
    <view
      v-for="item in masterTableList"
      :key="'detail-' + item.id"
      v-if="expandedRows.includes(item.id)"
      class="plan-form-container detail-section"
    >
      <view class="section-header">
        <text class="section-title">质检结果明细（{{ item.sampleCode || item.batchNo }}）</text>
      </view>

      <view class="table-container">
        <view class="table-header">
          <view class="header-cell" style="flex: 0.5">序号</view>
          <view class="header-cell" style="flex: 1.2">化学成分名称</view>
          <view class="header-cell" style="flex: 1">检验结果值</view>
          <view class="header-cell" style="flex: 1">下限</view>
          <view class="header-cell" style="flex: 1">上限</view>
          <view class="header-cell" style="flex: 0.8">单位</view>
          <view class="header-cell" style="flex: 1.2">分析方法</view>
        </view>

        <view class="table-body">
        <view
            v-for="(detail, detailIndex) in getDetailListBySampleId(item.id)"
            :key="detail.id || detailIndex"
          class="table-row"
          >
            <view class="table-cell" style="flex: 0.5">{{ detailIndex + 1 }}</view>
            <view class="table-cell" style="flex: 1.2">
              {{ detail.chemitemName || "-" }}
        </view>
            <view class="table-cell" style="flex: 1">
              {{ detail.chemitemValue || "-" }}
      </view>
            <view class="table-cell" style="flex: 1">
              {{ detail.lower !== null && detail.lower !== undefined ? detail.lower : "-" }}
            </view>
            <view class="table-cell" style="flex: 1">
              {{ detail.upper !== null && detail.upper !== undefined ? detail.upper : "-" }}
            </view>
            <view class="table-cell" style="flex: 0.8">{{ detail.meterUnit || "-" }}</view>
            <view class="table-cell" style="flex: 1.2">{{ detail.analyMethod || "-" }}</view>
          </view>

          <!-- 子表加载中 -->
          <view v-if="loadingDetails.includes(item.id)" class="empty-tip">
            <text>加载中...</text>
          </view>

          <!-- 子表空数据 -->
          <view
            v-if="
              !loadingDetails.includes(item.id) &&
              getDetailListBySampleId(item.id).length === 0
            "
            class="empty-tip"
          >
            <text>暂无明细数据</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { dateHelperApi } from "@/pages/smart/utils/date-helper";
import { PesSampleApi } from "@/api/qm/pessample";

export default {
  name: "TcQmReport",
  data() {
    return {
      // 查询表单
      searchForm: {
        sampleCode: "",
        furnaceNo: "",
        batchNo: "",
        steelGradeName: "",
        standName: "",
        createTimeStart: "",
        createTimeEnd: "",
      },

      // 主表数据列表
      masterTableList: [],

      // 子表数据列表（按 sampleId 分组）
      detailTableMap: {},

      // 展开的行ID列表
      expandedRows: [],

      // 正在加载明细的 sampleId 列表
      loadingDetails: [],

      // 分页信息
      pagination: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },

      // 加载状态
      loading: false,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },

    // 总页数
    totalPages() {
      return Math.ceil(this.pagination.total / this.pagination.pageSize) || 1;
    },
  },
  onLoad() {
    // 初始化时默认查询当天数据
    const today = dateHelperApi.getCurrentDate();
    this.searchForm.createTimeStart = today;
    this.searchForm.createTimeEnd = today;
    // 自动执行一次查询
    this.handleSearch();
  },
  methods: {
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return "";
      return dateHelperApi.formatDateTime(dateTime);
    },

    // 查询主表数据
    async handleSearch() {
      if (this.loading) return;

      this.loading = true;
      try {
        // 构建查询参数
        const params = {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize,
        };

        // 添加查询条件（只添加有值的字段）
        if (this.searchForm.sampleCode) {
          params.sampleCode = this.searchForm.sampleCode;
        }
        if (this.searchForm.furnaceNo) {
          params.furnaceNo = this.searchForm.furnaceNo;
        }
        if (this.searchForm.batchNo) {
          params.batchNo = this.searchForm.batchNo;
        }
        if (this.searchForm.steelGradeName) {
          params.steelGradeName = this.searchForm.steelGradeName;
        }
        if (this.searchForm.standName) {
          params.standName = this.searchForm.standName;
        }
        // 时间范围查询：如果有开始或结束时间，构建数组
        if (this.searchForm.createTimeStart || this.searchForm.createTimeEnd) {
          const timeArray = [];
          if (this.searchForm.createTimeStart) {
            // 开始时间：当天 00:00:00
            timeArray.push(this.searchForm.createTimeStart + " 00:00:00");
          }
          if (this.searchForm.createTimeEnd) {
            // 结束时间：当天 23:59:59
            timeArray.push(this.searchForm.createTimeEnd + " 23:59:59");
          }
          if (timeArray.length > 0) {
            params.createTime = timeArray;
          }
        }

        console.log("查询参数:", params);

        const response = await PesSampleApi.getPesSamplePage(params);

        if (response.code === 0 && response.data) {
          this.masterTableList = response.data.list || [];
          this.pagination.total = response.data.total || 0;

          // 如果查询结果为空，提示用户
          if (this.masterTableList.length === 0) {
        uni.showToast({
              title: "未查询到数据",
          icon: "none",
        });
          }
        } else {
        uni.showToast({
            title: response.msg || "查询失败",
          icon: "none",
        });
          this.masterTableList = [];
          this.pagination.total = 0;
      }
      } catch (error) {
        console.error("查询质检记录失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
        this.masterTableList = [];
        this.pagination.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 切换行展开/收起
    async toggleRowExpand(sampleId) {
      const index = this.expandedRows.indexOf(sampleId);
      if (index > -1) {
        // 收起
        this.expandedRows.splice(index, 1);
      } else {
        // 展开
        this.expandedRows.push(sampleId);
        // 如果还没有加载过该记录的明细，则加载
        if (!this.detailTableMap[sampleId]) {
          await this.loadDetailData(sampleId);
        }
      }
    },

    // 加载子表数据
    async loadDetailData(sampleId) {
      if (this.loadingDetails.includes(sampleId)) {
        return;
      }

      this.loadingDetails.push(sampleId);
      try {
        const params = {
          pageNo: 1,
          pageSize: 200, // 子表数据一般不会太多，设置一个较大的值
          sampleId: sampleId,
        };

        const response = await PesSampleApi.getPesSampleItemPage(params);

        if (response.code === 0 && response.data) {
          // 将子表数据存储到 map 中
          this.$set(this.detailTableMap, sampleId, response.data.list || []);
        } else {
            uni.showToast({
            title: response.msg || "加载明细失败",
              icon: "none",
            });
          this.$set(this.detailTableMap, sampleId, []);
        }
      } catch (error) {
        console.error("加载质检结果明细失败:", error);
        uni.showToast({
          title: "加载明细失败",
          icon: "none",
        });
        this.$set(this.detailTableMap, sampleId, []);
      } finally {
        const index = this.loadingDetails.indexOf(sampleId);
        if (index > -1) {
          this.loadingDetails.splice(index, 1);
        }
      }
    },

    // 根据 sampleId 获取子表列表
    getDetailListBySampleId(sampleId) {
      return this.detailTableMap[sampleId] || [];
    },

    // 重置查询条件
    handleReset() {
      const today = dateHelperApi.getCurrentDate();
      this.searchForm = {
        sampleCode: "",
        furnaceNo: "",
        batchNo: "",
        steelGradeName: "",
        standName: "",
        createTimeStart: today,
        createTimeEnd: today,
      };
      this.pagination.pageNo = 1;
      this.masterTableList = [];
      this.detailTableMap = {};
      this.expandedRows = [];
    },

    // 上一页
    handlePrevPage() {
      if (this.pagination.pageNo > 1) {
        this.pagination.pageNo--;
        this.handleSearch();
        // 滚动到顶部
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 300,
        });
      }
    },

    // 下一页
    handleNextPage() {
      if (this.pagination.pageNo < this.totalPages) {
        this.pagination.pageNo++;
        this.handleSearch();
        // 滚动到顶部
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 300,
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/pages/smart/scss/create.scss";

// 表格容器
.table-container {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-top: 20rpx;

  .table-header {
    display: flex;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20rpx 0;
    border-bottom: 2rpx solid rgba(255, 255, 255, 0.2);

    .header-cell {
      text-align: center;
      color: #000;
      font-size: 26rpx;
      font-weight: 600;
      padding: 0 8rpx;
    }
  }

  .table-body {
    .table-row {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f0f0f0;
      padding: 16rpx 0;
      transition: background-color 0.2s;

      &:hover {
        background-color: #f8f9fa;
      }

      &:last-child {
        border-bottom: none;
      }

      &.expanded {
        background-color: #f0f4ff;
      }

      .table-cell {
        text-align: center;
        font-size: 24rpx;
        color: #333;
        padding: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 60rpx;
        word-break: break-all;
      }
    }
  }
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;

  .pagination-info {
    font-size: 26rpx;
    color: #666;
  }

  .pagination-buttons {
    display: flex;
    gap: 20rpx;

    .pagination-btn {
      padding: 12rpx 24rpx;
      background: #667eea;
      color: #fff;
      border: none;
      border-radius: 8rpx;
      font-size: 26rpx;
      cursor: pointer;
      transition: all 0.2s;

      &:disabled {
        background: #ccc;
        cursor: not-allowed;
        opacity: 0.6;
      }

      &:active:not(:disabled) {
        background: #5568d3;
        transform: scale(0.95);
      }
    }
  }
}

// 明细区域
.detail-section {
  margin-top: 20rpx;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 空数据提示
.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 26rpx;
}

// 区域标题
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
  }

  .section-count {
    font-size: 24rpx;
    color: #666;
  }
}
</style>

